<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="编号" prop="number">
              <el-input v-model="queryParams.number" placeholder="请输入编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="归还时间" prop="arrivalTime" style="width: 308px">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_commit_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="applyTime" style="width: 308px">
              <el-date-picker v-model="createTimeRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['system:admAssetReturn:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['system:admAssetReturn:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['system:admAssetReturn:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['system:admAssetReturn:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="admAssetReturnList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="归还人" align="center" prop="returnId">
          <template #default="scope">
            <span>{{ scope.row.returnName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="归还日期" align="center" prop="returnTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="归还部门" align="center" prop="deptId">
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="归还项目" align="center" prop="projectId">
          <template #default="scope">
            <el-tooltip :content="scope.row.projectName" placement="top" :disabled="!scope.row.projectName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.projectName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="资产名称" align="center" prop="assetName">
          <template #default="scope">
            <el-tooltip :content="scope.row.assetName" placement="top" :disabled="!scope.row.assetName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.assetName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="编号" align="center" prop="number">
          <template #default="scope">
            <el-tooltip :content="scope.row.number" placement="top" :disabled="!scope.row.number">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.number }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="品牌" align="center" prop="brand" />
        <el-table-column label="序列号" align="center" prop="serialNumber">
          <template #default="scope">
            <el-tooltip :content="scope.row.serialNumber" placement="top" :disabled="!scope.row.serialNumber">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.serialNumber }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="approval_commit_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <template #default="scope">
            <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span
                  style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.remark }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:admAssetReturn:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:admAssetReturn:remove']"></el-button>
            </el-tooltip>
            <!-- 审批按钮 -->
            <el-tooltip content="提交审批" placement="top">
              <el-button
                link
                type="primary"
                icon="DocumentChecked"
                @click="openApprovalFlow(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改资产归还对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body class="seal-dialog">
      <template #default>
        <el-form ref="admAssetReturnFormRef" :model="form" :rules="rules" label-width="140px" label-position="left"
          style="padding: 20px 0 20px 24px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="归还人" prop="returnId">
                <el-input v-model="form.returnName" placeholder="请输入借用人" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="归还部门" prop="deptId">
                <el-tree-select
                  v-model="form.deptName"
                  :data="deptTree"
                  placeholder="请选择归还部门"
                  :props="{ label: 'label', value: 'id', children: 'children' }"
                  check-strictly
                  :editable="false"
                  :default-expand-all="true"
                  style="width: 100%"
                  @visible-change="handleVisibleChange"
                  @change="handleDeptChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="项目名称" prop="projectIdArray">
                <el-select
                  v-model="form.projectIdArray"
                  multiple
                  placeholder="请输入项目名称搜索"
                  clearable
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="searchProjects"
                  :loading="projectLoading"
                  style="width: 100%"
                  @change="handleProjectChange"
                >
                  <el-option
                    v-for="project in projectList"
                    :key="project.id"
                    :label="`${project.proName} (${project.proNumber || ''})`"
                    :value="String(project.id)"
                  />
                  <template #empty>
                    <div class="text-center p-2">
                      <span v-if="projectLoading">加载中...</span>
                      <span v-else-if="projectSearchKeyword && projectList.length === 0">未找到相关项目</span>
                      <span v-else>请输入项目名称进行搜索</span>
                    </div>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="归还日期" prop="returnTime">
                <el-date-picker clearable v-model="form.returnTime" type="date" value-format="YYYY-MM-DD" :editable="false"
                  placeholder="请选择归还日期" style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="资产名称" prop="assetName">
                <el-select v-model="form.assetName" placeholder="请选择资产" filterable clearable style="width: 100%"
                  @change="handleAssetChange">
                  <el-option v-for="item in assetOptions" :key="item.id" :label="item.assetName"
                    :value="item.assetName" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="编号" prop="number">
                <el-input v-model="form.number" placeholder="请输入编号" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="品牌" prop="brand">
                <el-input v-model="form.brand" placeholder="请输入品牌" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="序列号" prop="serialNumber">
                <el-input v-model="form.serialNumber" placeholder="请输入序列号" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核流程配置对话框 --> 
    <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="'ADM-ASSET-RETURN-AUDIT'"
      :business-id="auditIdForApproval" :key="auditIdForApproval" title="配置资产退还审核流程" @confirm="handleApprovalConfirm"
      @cancel="handleApprovalCancel" />
  </div>
</template>

<script setup name="AdmAssetReturn" lang="ts">
import { listAdmAssetReturn, getAdmAssetReturn, delAdmAssetReturn, addAdmAssetReturn, updateAdmAssetReturn } from '@/api/general/administration/asset/return';
import { AdmAssetReturnVO, AdmAssetReturnQuery, AdmAssetReturnForm } from '@/api/general/administration/asset/return/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';
import { pageListForQuery, getProInfo } from '@/api/project/init/proInfo';
import { resetApprovalStatus } from '@/components/ApprovalFlow/api';
import { listAssetBorrowSuccess } from '@/api/general/administration/asset/borrow';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const admAssetReturnList = ref<AdmAssetReturnVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const admAssetReturnFormRef = ref<ElFormInstance>();

// 用户信息
const userStore = useUserStore();

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 提交审核相关
const approvalFlowVisible = ref(false);
const currentSubmitAuditRow = ref<any>(null);
const auditIdForApproval = ref<string | number | undefined>(undefined);

// 搜索关键词
const projectSearchKeyword = ref('');
const flowSearchKeyword = ref('');
const projectLoading = ref(false);
const projectList = ref<ProInfoVO[]>([]);
// 防抖计时器
let projectSearchTimer: NodeJS.Timeout | null = null;
// 防止并发请求覆盖
let currentRequestId = 0;

// 引入数据字典
const { adm_item_type, approval_commit_status } = toRefs<any>(proxy?.useDict('adm_item_type', 'approval_commit_status'));

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

// 定义需要触发必填校验的部门名称或 ID
const requiredProjectDepts = ["董办", "综合办", "财务中心","商务中心"];
// 回显状态，防止重复调用
const backfillDone = ref(false);
// 资产列表
const assetOptions = ref([]);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: AdmAssetReturnForm = {
  id: undefined,
  returnId: userStore.userId,
  returnName: userStore.name,
  borrowId: undefined,
  returnTime: formatLocalDate(),
  deptId: userStore.deptId,
  deptName: userStore.deptName,
  projectIdArray: [] as string[],
  projectId: undefined,
  projectName: undefined,
  assetName: undefined,
  number: undefined,
  brand: undefined,
  serialNumber: undefined,
  remark: undefined,
  status: undefined,
  approverIdea: undefined,
}
const data = reactive<PageData<AdmAssetReturnForm, AdmAssetReturnQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    returnId: undefined,
    returnTime: undefined,
    deptId: undefined,
    assetName: undefined,
    number: undefined,
    brand: undefined,
    serialNumber: undefined,
    status: undefined,
    approverIdea: undefined,
    params: {
    }
  },
  rules: {
    serialNumber: [
      {
        required: false, message: "序列号不能为空", trigger: "blur"
      },
      {
        validator: (_rule, value, callback) => {
          if (value && /[\u4e00-\u9fa5]/.test(value)) {
            callback(new Error("序列号不能输入中文"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    number: [
      {
        required: true, message: "编号不能为空", trigger: "blur"
      },
      {
        validator: (_rule, value, callback) => {
          if (value && /[\u4e00-\u9fa5]/.test(value)) {
            callback(new Error("编号不能输入中文"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    returnId: [
      { required: true, message: "归还人不能为空", trigger: "blur" }
    ],
    returnTime: [
      { required: true, message: "归还日期不能为空", trigger: "change" }
    ],
    deptId: [
      { required: true, message: "部门不能为空", trigger: "change" }
    ],
    // 项目id
    projectIdArray: [
      { required: true, message: '请选择项目', trigger: 'change' }
    ],
    assetName: [
      { required: true, message: "资产名称不能为空", trigger: "blur" }
    ],
    brand: [
      { required: false, message: "品牌不能为空", trigger: "blur" }
    ]
  }
}
);

const { queryParams, form, rules } = toRefs(data);


/** 查询资产归还列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmAssetReturn(params);
    admAssetReturnList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  admAssetReturnFormRef.value?.resetFields();
}

/**
 * 检查是否需要触发 handleDeptChange 或补全项目数据
 * 触发条件：
 *   1. 部门存在
 *   2. 项目为空 → 调用 handleDeptChange
 *   3. 项目不为空 → 调用补全逻辑
 */
async function tryHandleDeptChange() {
  const deptId = form.value.deptId;
  const projectId = form.value.projectId;
  const isProjectEmpty =
    projectId === undefined ||
    projectId === null ||
    projectId === '' ||
    (Array.isArray(projectId) && projectId.length === 0);

  console.log('[tryHandleDeptChange] deptId:', deptId, 'projectId:', projectId, 'isProjectEmpty:', isProjectEmpty);

  if (deptId && isProjectEmpty) {
    console.log('[tryHandleDeptChange] 条件满足 → 触发 handleDeptChange');
    handleDeptChange(deptId);
  } else if (projectId) {
    console.log('[tryHandleDeptChange] 项目已存在 → 开始补全项目信息');
    await backfillProjectList(projectId);
  } else {
    console.log('[tryHandleDeptChange] 条件不满足 → 不执行任何操作');
  }
}

/**
 * 补全项目数据，仅用于已有 projectId 时的回显
 */
async function backfillProjectList(projectId: string | string[]) {
  try {
    backfillDone.value = true; // 防止重复调用
    // 转换成数组（支持字符串或数组）
    const ids = Array.isArray(projectId)
      ? projectId
      : projectId.split(',').map(id => id.trim()).filter(Boolean);

    console.log('[backfillProjectList] 待补全项目 ID 列表:', ids);
    const projectPromises = ids.map(id => getProInfo(Number(id)));
    const projectData = await Promise.all(projectPromises);
    projectData.forEach(res => {
      if (res?.data) {
        projectList.value.push({
          id: res.data.id,
          proName: res.data.proName,
          proNumber: res.data.proNumber,
          contractId: 0,
          contractName: '',
          projectRegion: '',
          proType: '',
          proContent: '',
          proPresidentsId: '',
          proLeadersId: '',
          ownerUnit: '',
          proAmount: null,
          proAmountRemark: '',
          proStatus: '',
          remark: '',
          createTime: '',
          createBy: ''
        });
      }
    });
    // ✅ 更新回显，不触发部门逻辑
    form.value.projectIdArray = ids.map(String);
    console.log('[backfillProjectList] 项目补全完成，projectIdArray:', form.value.projectIdArray);
  } catch (error) {
    console.error('[backfillProjectList] 项目补全失败:', error);
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdmAssetReturnVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加资产归还";
  tryHandleDeptChange()
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AdmAssetReturnVO) => {
  if (row.status != 4) {
    ElMessage.error("只能对审核不过的申请进行修改")
    return;
  } else {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getAdmAssetReturn(_id);
    Object.assign(form.value, res.data);
    tryHandleDeptChange();
    dialog.visible = true;
    dialog.title = "修改资产归还";
  }
}

/** 提交按钮 */
const submitForm = () => {
  admAssetReturnFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAdmAssetReturn(form.value).finally(() => buttonLoading.value = false);
        // 调用重置审核流程接口
        await resetApprovalStatus('ADM-ASSET-RETURN-AUDIT', Number(form.value.id), '不可审核')
      } else {
        console.log('提交表单', form.value);
        const res = await addAdmAssetReturn(form.value).finally(() => buttonLoading.value = false);
        // 触发审核流程配置对话框
        auditIdForApproval.value = res.data;
        approvalFlowVisible.value = true;
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

// 监听对话框关闭
watch(approvalFlowVisible, async (newVal, oldVal) => {
  if (oldVal && !newVal) {
    // 对话框从显示变成隐藏时刷新列表
    await getList();
  }
});

/** 删除按钮操作 */
const handleDelete = async (row?: AdmAssetReturnVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除资产归还编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmAssetReturn(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/admAssetReturn/export', {
    ...queryParams.value
  }, `admAssetReturn_${new Date().getTime()}.xlsx`)
}

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
      tree?.expandAll?.();
    }, 0);
  }
};

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 获取资产借阅成功列表
const fetchAssetOptions = async () => {
  try {
    const form: any = {
      borrowId: userStore.userId
    };
    const res = await listAssetBorrowSuccess(form); // 假设接口支持 params
    console.log("资产列表:", res.data);
    if (res.data && Array.isArray(res.data)) {
      assetOptions.value = res.data.map((item: any) => ({
        id: item.id,
        assetName: item.assetName,
        brand: item.brand,
        serialNumber: item.serialNumber,
        number: item.number,
        assetId: item.assetId
      }));
    }
    console.log("资产列表:", assetOptions.value);
  } catch (error) {
    console.error("获取资产列表失败:", error);
    proxy?.$modal.msgError("获取资产列表失败");
  }
};

// 选择资产后同步字段
const handleAssetChange = (selectedName: string) => {
  const selectedAsset = assetOptions.value.find(item => item.assetName === selectedName);
  if (selectedAsset) {
    form.value.assetName = selectedAsset.assetName;
    form.value.brand = selectedAsset.brand;
    form.value.serialNumber = selectedAsset.serialNumber;
    form.value.number = selectedAsset.number;
    form.value.assetId = selectedAsset.assetId;
    form.value.borrowId = selectedAsset.id;
  } else {
    form.value.brand = '';
    form.value.serialNumber = '';
  }
};

/** 审核流程确认回调 */
const handleApprovalConfirm = async () => {
  try {
    ElMessage.success('工作日志审核流程提交成功');
    approvalFlowVisible.value = false;
    currentSubmitAuditRow.value = null;
    auditIdForApproval.value = undefined;
  } catch (error) {
    console.error('审核流程提交失败:', error);
    ElMessage.error('审核流程提交失败');
  }
};

/** 审核流程取消回调 */
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentSubmitAuditRow.value = null;
  auditIdForApproval.value = undefined;
  // 审核流程取消时，表单已经在submitCurrentWorklogs中重置了，这里不需要重复重置
};

// 打开审批弹窗
const openApprovalFlow = (row?: AdmAssetReturnVO) => {
  if (row.status != 5){
    ElMessage.error('只能提交已导入的信息审批！');
    return;
  }
  auditIdForApproval.value = row.id;
  approvalFlowVisible.value = true;
};

// 部门选择处理（安全版）
const handleDeptChange = (selectedId: string | number) => {
  console.log('[handleDeptChange] 选中部门 ID:', selectedId);
  const selectedNode = findNodeById(deptTree.value, selectedId);
  if (!selectedNode) return;

  console.log('[handleDeptChange] 选中部门名称:', selectedNode.label);

  if (requiredProjectDepts.includes(selectedNode.label)) {
    console.log('[handleDeptChange] 部门在必填列表，触发项目搜索');
    searchProjects(selectedNode.label, true); // 传 true
  } else {
    console.log('[handleDeptChange] 部门不在必填列表，清空项目选择');
    form.value.projectIdArray = []; // 清空多选回显
    projectList.value = [];         // 可选：清空下拉列表
  }
};

// 遍历树查找节点
function findNodeById(tree: any[], id: string | number): any {
  for (const node of tree) {
    if (node.id === id) return node;
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) return found;
    }
  }
  return null;
}

/** 远程搜索项目 */
const searchProjects = (query: string, isDeptTrigger = false) => {
  projectSearchKeyword.value = query;
  if (projectSearchTimer) clearTimeout(projectSearchTimer);

  projectSearchTimer = setTimeout(() => {
    getProjectList(query || '', isDeptTrigger);
  }, 300);
};

// 获取项目列表
const getProjectList = async (searchKeyword = '', isDeptTrigger = false) => {
  try {
    projectLoading.value = true;
    const requestId = ++currentRequestId;

    const res = await pageListForQuery({
      pageNum: 1,
      pageSize: 50,
      flowStatus: '3',
      proName: searchKeyword || undefined
    });

    if (requestId !== currentRequestId) return; // 避免旧请求覆盖

    projectList.value = res.rows || [];
    console.log('[getProjectList] 接口返回项目列表数量:', projectList.value.length);

    if (isDeptTrigger) {
      // 部门触发搜索 → 全部项目 ID 回显
      form.value.projectIdArray = projectList.value.map(p => String(p.id));
      console.log('[回显] 部门触发 projectIdArray:', form.value.projectIdArray);
    } else if (!backfillDone.value && form.value.projectIdArray?.length) {
      // 回显逻辑：检查本地是否匹配全部 ID
      const missingIds = form.value.projectIdArray.filter(
        id => !projectList.value.some(p => String(p.id) === id)
      );

      if (missingIds.length > 0) {
        console.log('[getProjectList] 有缺失项目，需要调用搜索补全:', missingIds);
        backfillDone.value = true; // 标记已经补全，避免循环

        // 调用远程接口补全
        const projectPromises = missingIds.map(id => getProInfo(Number(id)));
        const projectData = await Promise.all(projectPromises);

        // 将补全的数据加入项目列表并更新回显
        projectData.forEach(res => {
          if (res?.data) {
            projectList.value.push({
              id: res.data.id,
              proName: res.data.proName,
              proNumber: res.data.proNumber,
              contractId: 0,
              contractName: '',
              projectRegion: '',
              proType: '',
              proContent: '',
              proPresidentsId: '',
              proLeadersId: '',
              ownerUnit: '',
              proAmount:  null,
              proAmountRemark: '',
              proStatus: '',
              remark: '',
              createTime: '',
              createBy: ''
            });
          }
        });

        // 确保回显
        form.value.projectIdArray = [...form.value.projectIdArray];
        console.log('[getProjectList] 补全完成，停止回显循环');
      } else {
        console.log('[getProjectList] 本地列表匹配到全部 projectId，回显完成');
        backfillDone.value = true;
      }
    }
  } catch (error) {
    console.error('获取项目列表失败:', error);
    ElMessage.error('获取项目列表失败');
  } finally {
    projectLoading.value = false;
  }
};

/** 处理项目选择变化 */
const handleProjectChange = (value: number | string | undefined) => {
  flowSearchKeyword.value = ''; // 清空流程搜索关键词

  // 项目改变时不清空工作日志列表，允许多个项目的数据共存
};

onMounted(() => {
  getList();
  fetchDeptTree();
  fetchAssetOptions();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block;
  /* 确保是块级元素 */
}
</style>